import { HttpClient, HttpHandler, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Park } from './park';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin'

/*
  Generated class for the ParkDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ParkDataProvider {


  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders(
    {
      'X-Bmob-Application-Id':'7005414afe8e71b660439aac975c101f',
      'X-Bmob-REST-API-Key':'571bf16525c62447573dba6977e7e38e',
      'Content-Type':'application/json'
    }
  );

  constructor(public http: HttpClient) {
    
  }

  // 返回多个数据
  /**
   * 分页获取景区数据
   * @param num 
   * @param page 
   */
  getParks(num : number, page: number):Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${(page-1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
    {headers: this.httpHeaders, params: _params}).map(_=>_['results']);
  }

  /**
   * 获取纪录条数
   */
  getCount(): Observable<number>{
    return this.http.get<number>(`${this.baseUrl}/classes/parks?limit=0&count=1`,{headers: this.httpHeaders}).map(data=>data['count']);
  }

  /**
   * 获取所有纪录
   * @param total 纪录总数
   */
  getAllParks(total:number):Observable<Park[][]>{
    let num = 500;
    let all: Observable<Park[]>[]=[];
    for (let index = 0; index < total / num; index++) {
      let _params = new HttpParams()
        .set('limit',`${num}`)
        .set('skip',`${index*num}`);
      all[index] = this.http.get<Park[]>
      (`${this.baseUrl}/classes/parks`,{headers: this.httpHeaders,params:_params}).map(_ => _['results']);
    }
    return Observable.forkJoin(all);
  }



}
